package com.drg.center.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.drg.center.dao.SysIndexDAO;
import com.drg.center.entity.param.SysIndexAddDTO;
import com.drg.center.entity.param.SysIndexEditDTO;
import com.drg.center.entity.result.SysIndexVO;
import com.guaike.core.entity.param.Page;
import com.guaike.core.entity.result.PageEntity;
import com.guaike.core.entity.result.Result;
import com.guaike.core.utils.ListUtil;
import com.drg.center.entity.SysIndexPO;
import com.drg.center.service.SysIndexService;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author: zhangxilin
 * @Date: 2024/5/21
 */
@Slf4j
@Service
public class SysIndexServiceImpl implements SysIndexService {

    @Autowired
    private SysIndexDAO sysIndexDAO;

    @Override
    public Result<PageEntity<SysIndexVO>> findPage(Page page) {
        IPage<SysIndexPO> iPage = sysIndexDAO.findPage(page.getPageIndex(), page.getPageSize());
        if(CollectionUtils.isEmpty(iPage.getRecords())){
            return Result.success().data(new PageEntity<>(iPage.getTotal(), Lists.newArrayList())).build();
        }
        List<SysIndexVO> list = ListUtil.copyList(iPage.getRecords(), SysIndexVO.class);
        return Result.success().data(new PageEntity<>(iPage.getTotal(), list)).build();
    }

    @Override
    public Result<SysIndexVO> detail(Long id) {
        SysIndexPO po = sysIndexDAO.findById(id);
        if(po==null){
            return Result.failure().message("记录不存在").build();
        }
        SysIndexVO vo = new SysIndexVO();
        BeanUtil.copyProperties(po,vo);
        return Result.success().data(vo).build();
    }

    @Override
    public Result<Boolean> add(SysIndexAddDTO param) {
        if(sysIndexDAO.isExist(param.getSysCode(), null)){
            return Result.failure().message("系统编号已存在").build();
        }
        SysIndexPO record = new SysIndexPO();
        BeanUtil.copyProperties(param,record);
        sysIndexDAO.save(record);
        return Result.success().data(Boolean.TRUE).build();
    }

    @Override
    public Result<Boolean> edit(SysIndexEditDTO param) {
        if(sysIndexDAO.isExist(param.getSysCode(), param.getId())){
            return Result.failure().message("系统编号已存在").build();
        }
        SysIndexPO record = sysIndexDAO.findById(param.getId());
        if(record==null){
            return Result.failure().message("记录不存在").build();
        }
        BeanUtil.copyProperties(param,record);
        sysIndexDAO.updateById(record);
        return Result.success().data(Boolean.TRUE).build();
    }
}
